package com.emm.yixun.customer.service.impl;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.basic.service.QuestionnaireAnswerService;
import com.emm.yixun.basic.service.QuestionnaireModelService;
import com.emm.yixun.basic.service.QuestionnaireQuestionService;
import com.emm.yixun.common.model.QuestionnaireAnswer;
import com.emm.yixun.common.model.QuestionnaireQuestion;
import com.emm.yixun.common.model.QuestionnaireQuestionInfo;
import com.emm.yixun.common.model.dto.QuestionnaireAnswerDto;
import com.emm.yixun.common.model.dto.QuestionnaireModelDto;
import com.emm.yixun.common.model.dto.QuestionnaireQuestionDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IsAvlidEnum;
import com.emm.yixun.customer.service.QuestionnaireQuestionServiceFacade;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("questionnaireQuestionServiceFacade")
@WebService(name="com.emm.yixun.customer.service.QuestionnaireQuestionServiceFacade")
public class QuestionnaireQuestionServiceFacadeImpl implements QuestionnaireQuestionServiceFacade{
	private  final Logger   logger = LoggerFactory.getLogger(this.getClass()); 
	
	@Autowired
	private QuestionnaireQuestionService service;
	@Autowired
	private QuestionnaireAnswerService questionnaireAnswerservice;
	@Autowired
	private QuestionnaireModelService questionnaireModelService;

	@Override
	public Response<QuestionnaireQuestionDto> save(QuestionnaireQuestionDto dto) {
		Response<QuestionnaireQuestionDto> response=new Response<QuestionnaireQuestionDto>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			QuestionnaireQuestionDto mDto=service.create(dto);
			if(null==mDto){
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(QuestionnaireQuestionDto dto,Boolean selective) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==selective || null==dto || null==dto.getId()){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}
			
			if(selective){
				int count=service.update(dto);
				if(count>0){
					response.success(Integer.valueOf(count));
				}else{
					response.fail("90001", "更新数据失败");
				}
			}else{
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response=new Response<Integer>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			QuestionnaireQuestionDto mDto=new QuestionnaireQuestionDto();
			mDto.setId(id);
			int count=service.destroy(mDto);
			if(count>0){
				response.success(Integer.valueOf(count));
			}else{
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}",e);
		}
		return response;
	}
	
    @Override
	public Response<QuestionnaireQuestion> findById(Long id) {
		Response<QuestionnaireQuestion> response=new Response<QuestionnaireQuestion>();
		try {
			if(null==id){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			QuestionnaireQuestion entity=service.selectById(id);
			if(null==entity){
				response.fail("90001", "主键查询数据失败");
			}else{
				response.success(entity);;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public ResponseList<QuestionnaireQuestion> findByDto(QuestionnaireQuestionDto dto) {
		ResponseList<QuestionnaireQuestion> response=new ResponseList<QuestionnaireQuestion>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<QuestionnaireQuestion> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Page<QuestionnaireQuestion> findPageByDto(QuestionnaireQuestionDto dto, Integer begin,Integer row) {
		Page<QuestionnaireQuestion> response=new Page<QuestionnaireQuestion>();
		try {
			if(null==dto || null==begin || null==row){
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<QuestionnaireQuestion> page = service.getPageModel(dto, begin, row);
			if(null==page.getRows()){
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response=page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}",e);
		}
		return response;
	}

	@Override
	public Response<String> saveQuestionnaire(QuestionnaireQuestionInfo info) {
		Response<String> response=new Response<String>();
		try {
			if(null==info){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			//保存问题及答案
			saveQuestion(info);
			
			//更新模板修改人与修改时间
			QuestionnaireModelDto model = new QuestionnaireModelDto();
			model.setId(info.getQuestionnaireModelId());
			model.setUpdateUser(info.getCreateUser());
			model.setUpdateTime(info.getCreateTime());
			questionnaireModelService.update(model);
			
			response.success("1");
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}",e);
		}
		return response;
	}
	/**
	 * 保存问卷
	 * @param QuestionnaireQuestionInfo
	 * @return
	 */
	private Response<String> saveQuestion(QuestionnaireQuestionInfo info){
		Response<String> response = new Response<String>();
		//判断问卷是否已保存过，如已保存，则删除原纪录(逻辑删除)
		QuestionnaireQuestionDto entity = new QuestionnaireQuestionDto();
		entity.setQuestionnaireModelId(info.getQuestionnaireModelId());
		List<QuestionnaireQuestion> list = service.selectListByDto(entity);
		for(int i = 0; i < list.size(); i++){
			QuestionnaireQuestion question = (QuestionnaireQuestion)list.get(i);
			QuestionnaireQuestionDto dto = new QuestionnaireQuestionDto();
			dto.setId(question.getId());
			dto.setIsValid(IsAvlidEnum.UNAVILD.getNo());
			dto.setDelFlag(DelFlagEnum.DEL.getNo());
			service.update(dto);
			
			//删除已保存的答案
			QuestionnaireAnswerDto answerEntity = new QuestionnaireAnswerDto();
			answerEntity.setQuestionnaireQuestionId(question.getId());
			List<QuestionnaireAnswer> answerList = questionnaireAnswerservice.selectListByDto(answerEntity);
			for(int l = 0; l < answerList.size(); l++){
				QuestionnaireAnswer answer = (QuestionnaireAnswer)answerList.get(l);
				QuestionnaireAnswerDto answerDto = new QuestionnaireAnswerDto();
				answerDto.setId(answer.getId());
				answerDto.setIsValid(IsAvlidEnum.UNAVILD.getNo());
				answerDto.setDelFlag(DelFlagEnum.DEL.getNo());
				questionnaireAnswerservice.update(answerDto);
			}
		}
		
		//解析arrayJson，获取问题内容，并循环保存
		JSONArray array = JSONArray.fromObject(info.getArrayJson());
		for(int i = 0; i < array.size(); i++){
			JSONObject json = (JSONObject)array.get(i);
			QuestionnaireQuestionDto dto = new QuestionnaireQuestionDto();
			dto.setQuestionnaireModelId(info.getQuestionnaireModelId()); //模板主表ID
			dto.setQuestion(json.getString("question")); //问题名称
			dto.setQuestionnaireDescribe(json.get("questionnaireDescribe") == null?
					"":json.getString("questionnaireDescribe")); //问题描述
			dto.setProblemCode(json.getString("problemCode")); //问题编码
			dto.setAnswerType(json.getString("answerType")); //答案类型
			dto.setIsRequired(json.getString("isRequired")); //是否必填
			dto.setLevel(Long.parseLong(json.getString("level"))); //问题级别
			dto.setTagExtId(StringUtils.isBlank(json.getString("tagExtId"))?
                    null:Long.parseLong(json.getString("tagExtId"))); //客户标签问题ID
			dto.setSort(Long.parseLong(i+1+"")); //排序
			dto.setPage(1L); //分页（默认为1页）
			dto.setMerchantId(info.getMerchantId()); //商户ID
			dto.setCreateTime(info.getCreateTime());
			dto.setCreateUser(info.getCreateUser());
			dto.setIsValid(IsAvlidEnum.AVILD.getNo());
			dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			QuestionnaireQuestionDto qq = service.saveQuestion(dto);
			//保存答案
			saveAnswer(json.getString("answer"), qq);
		}
		
		response.success("1");
		return response;
	}
	
	/**
	 * 保存答案
	 * @param arrayJson
	 * @param id
	 * @param merchantId
	 * @return
	 */
	private Response<String> saveAnswer(String arrayJson, QuestionnaireQuestionDto qq){
		Response<String> response = new Response<String>();
		//删除原答案
		QuestionnaireAnswerDto entity = new QuestionnaireAnswerDto();
		entity.setQuestionnaireQuestionId(qq.getId());
		List<QuestionnaireAnswer> list = questionnaireAnswerservice.selectListByDto(entity);
		for(int i = 0; i < list.size(); i++){
			QuestionnaireAnswer answer = (QuestionnaireAnswer)list.get(i);
			QuestionnaireAnswerDto dto = new QuestionnaireAnswerDto();
			dto.setId(answer.getId());
			questionnaireAnswerservice.destroy(dto);
		}
		//解析json，并保存新答案
		JSONArray array = JSONArray.fromObject(arrayJson);
		for(int i = 0; i < array.size(); i++){
			String answer = array.get(i).toString();
			if(StringUtils.isBlank(answer)){
				continue;
			}
			QuestionnaireAnswerDto dto = new QuestionnaireAnswerDto();
			dto.setQuestionnaireQuestionId(qq.getId()); //问题ID
			dto.setAnswer(answer);	//答案内容
			dto.setSort(Long.parseLong(i+1+"")); //排序
			dto.setMerchantId(qq.getMerchantId()); //商户ID
			dto.setCreateTime(qq.getCreateTime());
			dto.setCreateUser(qq.getCreateUser());
			dto.setIsValid(IsAvlidEnum.AVILD.getNo());
			dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			questionnaireAnswerservice.create(dto);
		}
		return response;
	}
	
	@Override
	public ResponseList<QuestionnaireQuestionInfo> questionList(QuestionnaireQuestionDto dto) {
		ResponseList<QuestionnaireQuestionInfo> response=new ResponseList<QuestionnaireQuestionInfo>();
		try {
			if(null==dto){
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<QuestionnaireQuestionInfo> infoList = new ArrayList<QuestionnaireQuestionInfo>();
			dto.addAsc("sort");
			List<QuestionnaireQuestion> list=service.selectListByDto(dto);
			if(null==list){
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			for(QuestionnaireQuestion question : list){
				QuestionnaireQuestionInfo info = new QuestionnaireQuestionInfo();
				BeanUtils.copyProperties(question, info);
				
				//查询答案表
				QuestionnaireAnswerDto answerDto = new QuestionnaireAnswerDto();
				answerDto.setQuestionnaireQuestionId(question.getId()); //问题ID
				answerDto.setIsValid(IsAvlidEnum.AVILD.getNo());
				answerDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				List<QuestionnaireAnswer> answerList = questionnaireAnswerservice.selectListByDto(answerDto);
				JSONArray arrayJson = new JSONArray(); //保存答案ID和内容
				JSONArray array = new JSONArray(); //仅保存答案内容
				for(QuestionnaireAnswer answer : answerList){
					JSONObject json = new JSONObject();
					json.put("id", answer.getId());
					json.put("answer", answer.getAnswer());
					arrayJson.add(json);
					array.add(answer.getAnswer());
				}
				info.setAnswer(array.toString());
				info.setArrayJson(arrayJson.toString());
				infoList.add(info);
			}
			
			response.success(infoList);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}",e);
		}
		return response;
	}

}
